<template>
	<view class="container">
		<view class="head mb-30">
			<view class="tabs flex align-end">
				<view
					class="item w-50 flex justify-center align-center sel"
					:class="current === index ? item.style1 : item.style2"
					v-for="(item, index) in tabList"
					:key="item.id"
					@click="onTabs(index)"
				>
					<image class="width-30 height-30" :src="current === index ? item.icon2 : item.icon1"></image>
					<text class="ml-10">{{ item.name }}</text>
				</view>
			</view>
			<view class="bg-white border-radius-br-10 border-radius-bl-10 padding-30 height-148">
				<view class="flex" v-if="current === 0">
					<view class="w-50 flex justify-between">
						<view>
							<view class="fsize-32 fweigh-600">堂食台号</view>
							<view class="fsize-22 line-gray mt-10">餐品将送至您的餐台</view>
						</view>
						<view style="border-right: 1px #ededed solid; width: 1px"></view>
					</view>
					<view class="w-50 flex justify-between align-center">
						<text class="w-100 fsize-40 text-align-center fweigh-600">#{{ stock.deskNumber }}</text>
						<!-- 台号-->
						<image class="width-30 height-30 shrink0" src="../../static/images/my/icon_arrow.png"></image>
					</view>
				</view>
				<view class="" v-if="current === 1">
					<view class="flex align-center">
						<text class="fsize-28 fweigh-600">{{ stock.storeName }}</text>
						<image class="width-30 height-30 shrink0" src="../../static/images/my/icon_arrow.png"></image>
					</view>
					<view class="mt-10 fsize-24 line-gray">{{ stock.address }}</view>
				</view>
			</view>
		</view>

		<!-- 未下单 -->
		<view class="mb-30 bg-white border-radius-10">
			<!-- 必选商品 -->
			<view class="padding-30" v-if="defaultList.length > 0">
				<view style="color: #b1b1b1; font-size: 30rpx">默认菜品（{{ defaultList.length }}）</view>
				<scroll-view scroll-y style="max-height: 500rpx">
					<view style="display: flex; justify-content: space-between; line-height: 60rpx" v-for="(item, index) in defaultList" :key="index">
						<view>
							<text style="margin-right: 8rpx">{{ item.fName }}</text>
							<text class="fsize-28" style="margin-right: 10rpx" :class="{ del: (item.vipPrice && userInfo.id) || item.discountPrice }">￥{{ item.fPosPrice }}</text>
							<text class="fsize-28" style="color: #ed4d4f" v-if="item.discountPrice">特价优惠￥{{ item.discountPrice }}</text>
							<text class="fsize-28" style="color: #ed4d4f" v-if="item.vipPrice && !item.discountPrice">会员价￥{{ item.vipPrice }}</text>
							<!-- <text style="color: #ed4d4f;">￥{{ item.vipPrice === 0 ? item.fPosPrice :  item.vipPrice}}</text> -->
						</view>
						<view class="num-btn">
							<!-- v-show="number" v-show="number"-->
							<view class="number line-gray">×{{ item.fQty }}</view>
						</view>
					</view>
				</scroll-view>
			</view>

			<view class="notPlace">
				<view class="padding-30" style="color: #b1b1b1; font-size: 30rpx">未下单（{{ cart.length }}）</view>

				<view class="padding-30" v-for="(item, index) in cart" :key="item.id">
					<view class="flex w-100">
						<image class="width-88 height-88 shrink0 mr-10" :src="item.FPic"></image>
						<view class="w-100 flex justify-between">
							<view style="display: flex; flex-direction: column; justify-content: space-between">
								<view class="fsize-28">{{ item.FName }}</view>
								<view class="fsize-20 line-gray" v-if="item.foodType === 1">{{ item.FSpec }} {{ item.FeedTasteNames }}</view>
								<view class="fsize-20 line-gray" v-else>
									{{ detailList[index].map((v) => v.foodName + '× ' + v.quantity) }}
								</view>
							</view>
							<view class="flex flex-column justify-between shrink0 ml-10 text-align-right">
								<view>
									<text style="margin-right: 10rpx" class="line-gray">
										<text class="fsize-18">￥</text>
										<text class="fsize-24" :class="{ del: (item.vipPrice && userInfo.id) || item.discountPrice }">{{ item.FPosPrice }}</text>
									</text>
									<text v-if="item.discountPrice" style="color: #ed4d4f">
										<text class="fsize-20">特价优惠￥</text>
										<text class="fsize-28">{{ item.discountPrice }}</text>
									</text>
									<text v-if="item.vipPrice && !item.discountPrice" style="color: #ed4d4f">
										<text class="fsize-20">会员价￥</text>
										<text class="fsize-28">{{ item.vipPrice }}</text>
									</text>
								</view>
								<text class="fsize-26 line-gray">x{{ item.number }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 推荐菜 -->
			<!-- 菜品推荐 -->
			<view style="padding: 10rpx">
				<view class="recommend-box" v-if="recommendList.length > 0">
					<view class="title">商品推荐</view>
					<view class="padding-30" v-for="(item, index) in recommendList" :key="item.id">
						<view class="flex w-100">
							<image style="border-radius: 10rpx" class="width-109 height-109 shrink0 mr-10" :src="item.image"></image>
							<view class="w-100 flex justify-between">
								<view class="w-100" style="display: flex; flex-direction: column; justify-content: space-between">
									<view class="fsize-28" style="display: flex; align-items: center">
										<view class="special-box" v-if="item.vipPrice">会员特价</view>
										<view>{{ item.name }}</view>
									</view>
									<view v-if="item.vipPrice || item.discountPrice" style="font-size: 22rpx; color: #999999">
										<text class="fsize-20">￥</text>
										<text :class="{ del: (item.vipPrice && userInfo.id) || item.discountPrice }">{{ item.price }}</text>
									</view>
									<text v-if="item.discountPrice" style="font-size: 24rpx; color: #111">
										￥{{ item.discountPrice }}
										<text style="color: #eeb139; font-size: 20rpx; margin-left: 10rpx">特价优惠</text>
									</text>
									<text v-else style="font-size: 24rpx; color: #111">
										￥{{ item.vipPrice || item.price }}
										<text v-if="item.vipPrice" style="color: #eeb139; font-size: 20rpx; margin-left: 10rpx">推荐</text>
									</text>
									<!-- <text class="fsize-26 line-gray">x{{item.number}} </text> -->
								</view>
								<view style="display: flex; align-items: flex-end">
									<Action :number="item.number" :materialsBtn="false" @minus="onMinus(item, index)" @add="onAdd(item, index)"></Action>
									<ProductPopup @cancel="closeVisable" @addToCart="addToCart" :visible="isVisable" :product="productData"></ProductPopup>
								</view>
							</view>
						</view>
					</view>
					<view class="more">
						<u-icon
							@click="onMore"
							label="展示更多"
							:name="isMore ? 'arrow-down' : 'arrow-up'"
							labelSize="24rpx"
							labelColor="#999999"
							color="#999999"
							size="12px"
							labelPos="left"
							space="5px"
						></u-icon>
					</view>
				</view>
			</view>

			<!-- 已下单 -->
			<view class="placeOrder" v-if="orderedList.length > 0">
				<view class="padding-30 is-show">
					<view class="">已下单（{{ orderedList.length }}）</view>
					<u-icon
						color="#b1b1b1"
						label-size="14"
						labelColor="#b1b1b1"
						:label="isShow ? '不展示' : '展示'"
						:name="isShow ? 'arrow-down' : 'arrow-up'"
						@click="isShow = !isShow"
						labelPos="left"
					></u-icon>
				</view>
				<view v-if="isShow">
					<view class="padding-30" v-for="(item, index) in orderedList" :key="item.id">
						<view class="flex w-100">
							<image class="width-88 height-88 shrink0 mr-10" :src="item.image"></image>
							<view class="w-100 flex justify-between">
								<view style="display: flex; justify-content: space-between; flex-direction: column">
									<view class="fsize-28">{{ item.name }}</view>
									<view class="fsize-20 line-gray" v-if="item.itemType === 1">{{ item.specName }}{{ item.feedTasteNames }}</view>
									<view class="fsize-20 line-gray" v-else>{{ orderDetailList[index].map((v) => v.foodName + '× ' + v.quantity) }}</view>
									<!-- {{ item.FeedTasteNames }} -->
								</view>
								<view class="flex flex-column justify-between shrink0 ml-10 text-align-right">
									<view>
										<text class="fsize-18">￥</text>
										<text class="fsize-28">{{ item.allAmount }}</text>
									</view>
									<text class="fsize-26 line-gray">x{{ item.quantity }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 	<list-cell last> 优惠券
				<view class="w-100 flex justify-between">
					<text class="fsize-28">优惠卷</text>
					<view class="flex align-center" @click="
              $u.route('/pages/user/coupon/coupon', {
                tickets: JSON.stringify(coupons),
              })
            ">
						<text v-if="!coupon.id" class="fsize-24 line-gray">{{
              coupons.length > 0 ? coupons.length + "张" : "暂无可用"
            }}</text>
						<text v-else class="fsize-24 line-red">
							-￥{{ coupon.reduceAmount }}
						</text>
						<image class="width-30 height-30 shrink0" src="../../static/images/my/icon_arrow.png"></image>
					</view>
				</view>
			</list-cell> 
			展示总价
			<list-cell last>
				<view class="w-100 flex justify-end align-center fsize-26">
					<text class="">共{{ cartNum }}件商品，合计</text>
					<view class="fweigh-600">
						<text class="fsize-30">￥</text>
						<text class="fsize-40">{{ cartAmount.toFixed(2) }}</text>
					</view>
				</view>
			</list-cell>
			-->
		</view>
		<!-- 	<view style="padding-bottom: 30rpx">
			<list-cell last radius>
				<view class="w-100 flex justify-between align-center">
					<text class="fsize-28">备注</text>
					<view class="flex align-center">
						<text class="fsize-24 mr-10" v-if="!remark">--</text>
						<text class="fsize-24 mr-10" v-else-if="remark && remark.length < 5">{{ remark }}</text>
						<text class="fsize-24 mr-10" v-else>{{ remark.substring(0, 5) }}...</text>
						<image class="width-30 height-30 shrink0" src="../../static/images/my/icon_arrow.png" @click="onRemark">
						</image>
					</view>
				</view>
			</list-cell>
		</view> -->
		<view class="footer" :style="">
			<view>
				<!-- <text>应付：</text>
				<text class="fweigh-600">
					<text class="fsize-30">￥</text>
					<text class="fsize-40">{{ cartAmount.toFixed(2) }}</text>
				</text> -->
				<button @click="addFoods">继续加菜</button>
			</view>
			<!-- 点击下单，跳转到订单详情界面 order/detail-->
			<button class="button" @click="submitOrder" :disabled="disabled">提交订单</button>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import { mapState } from 'vuex';
import listCell from '@/components/list-cell/list-cell.vue';
import Action from '@/pages/tab_bar/classify/components/actions/actions.vue';
import ProductPopup from '@/pages/tab_bar/classify/components/product-popup/product-popup.vue';
// import {requestPayment} from "@/utils/payment";
import { pay } from '@/common/util.js';
export default {
	components: {
		listCell,
		Action,
		ProductPopup
	},
	data() {
		return {
			isVisable: false, // 弹出加入购物车
			productData: {},
			isMore: false, // 是否展示更多推荐
			recommendList: [], // 推荐数组
			allRecommendList: [],
			disabled: false,
			deskId: 0,
			orderId: 0,
			isShow: false, // 展示已下单商品
			orderedList: [], // 已下单数据
			defaultList: [], // 默认菜品
			current: 0,
			FType: 1,
			timer: null,
			tabList: [
				{
					id: 1,
					name: '堂食',
					icon1: '../../static/images/pay/ts-s.png',
					icon2: '../../static/images/pay/ts.png',
					style1: 'sel',
					style2: 'nosel'
				},
				{
					id: 2,
					name: '外带',
					icon1: '../../static/images/pay/dd-s.png',
					icon2: '../../static/images/pay/dd.png',
					style1: 'ser',
					style2: 'noser'
				}
			],
			cart: [],
			coupons: [],
			coupon: {
				id: 0,
				reduceAmount: 0
			}
		};
	},
	onReady() {
		// #ifdef MP-ALIPAY
		uni.hideHomeButton();
		uni.setNavigationBarColor({
			frontColor: '#000000', // 设置文本颜色
			backgroundColor: '#ffffff' // 设置背景颜色
		});
		// #endif
	},
	computed: {
		...mapState(['stock', 'orderType', 'userInfo', 'classType']),
		// 总数量
		cartNum() {
			return this.cart.reduce((acc, cur) => acc + cur.number, 0);
		},
		// 总价
		cartAmount() {
			return this.cart.reduce((acc, cur) => acc + cur.number * cur.FPosPrice, 0) - this.coupon.reduceAmount;
		},
		// 计算套菜的规格
		detailList() {
			const list = this.cart.map((row) => {
				if (!row.detailList) return [];
				return row.detailList.map((v) => {
					return {
						foodName: v.foodName,
						quantity: v.quantity
					};
				});
			});
			return list || [];
		},
		orderDetailList() {
			const list = this.orderedList.map((row) => {
				if (!row.detailList) return [];
				return row.detailList.map((v) => {
					return {
						foodName: v.name,
						quantity: v.quantity
					};
				});
			});
			return list || [];
		}
	},
	onShow() {
		this.orderId = uni.getStorageSync('orderId') || 0;
		this.deskId = uni.getStorageSync('deskId') || 0;
		Promise.all([this.getCat(), this.getOrdered(), this.getFoodCartShopCouponList()]);
		// this.FType = this.orderType;
		this.FType = this.classType;
		this.current = this.FType === 2 ? 1 : 0;
		+uni.$on('isRefresh', (data) => {
			this.coupon = data;
		});
	},
	onUnload() {
		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
		uni.$off('isRefresh');
	},
	methods: {
		getCat() {
			// this.$api.GetShoppingCart().then(res=>{
			// this.cart = res.data.length === 0?[]:res.data.map(im=>{
			this.$api
				.GetShoppingCart({
					deskId: this.deskId
				})
				.then((res) => {
					this.defaultList = res.data.defaultList;
					this.cart =
						res.data.foodList.length === 0
							? []
							: res.data.foodList.map((im) => {
									return {
										vipPrice: im.vipPrice,
										FItemID: im.fSubItemID,
										FFoodID: im.fFoodID,
										FName: im.fName,
										FPosPrice: im.fPosPrice,
										number: im.fQty,
										FPic: im.fProImage,
										FSpec: im.fSpec,
										FFoodSpecID: im.fFoodSpecID,
										FRemark: im.fRemark,
										FeedTasteNames: im.feedTasteNames,
										FShoppingCartID: im.fShoppingCartID || 0,
										feed_ids: im.feedData.length > 0 ? im.feedData.map((jm) => jm.fFeedID) : [],
										tast_ids: im.tastData.length > 0 ? im.tastData.map((jm) => jm.fTastID) : [],
										detailList: im.detailList || [],
										foodType: im.foodType,
										discountPrice: im.discountPrice
									};
							  });
					this.allRecommendList = res.data.recommendList;
					this.allRecommendList.map((v) => this.$set(v, 'number', 0));
					this.recommendList = JSON.parse(JSON.stringify(this.allRecommendList.slice(0, 3)));
				});
		},
		onTabs(ix) {
			if (this.current !== ix) {
				this.current = ix;
				if (ix === 0) {
					this.FType = 1;
				} else {
					this.FType = 2;
				}
			}
		},
		placeOrder() {
			//   let _this = this;
			//   _this.$api
			//     .placeOrder({
			//       FType: _this.FType,
			//       FDeskID: _this.stock.deskId,
			//       FCouponID: _this.coupon.id,
			//       reduceAmount: _this.coupon.reduceAmount,
			//     })
			//     .then((res) => {
			//       pay(res.data.orderId);
			// _this.$api.OrderPay({ids: res.data.orderId, payment_code: 'wechatpay', payment_type:17,params:{}}).then(respay=>{
			// 	const params = respay.data.respData
			// 	// 天厥收银台支付
			// 	uni.openEmbeddedMiniProgram({
			// 		appId: params.appId,
			// 		path: params.path,
			// 		success(res) {
			// 打开成功
			// _this.onToast('调取支付成功!')
			// uni.switchTab({
			// 	url: '/pages/tab_bar/order/order'
			// });
			// 	}
			// })
			// uni.requestPayment({
			// 	provider: 'wxpay',
			// 	timeStamp: params.payTimeStamp,
			// 	nonceStr: params.paynonceStr,
			// 	package: params.payPackage,
			// 	signType: params.paySignType,
			// 	paySign: params.paySign,
			// 	success: function(sucs) {
			// 		_this.onToast('支付成功')
			// 	},
			// 	fail: function(fail) {
			// 		if(fail.errMsg === 'requestPayment:fail cancel'){
			// 			_this.onToast('已取消支付')
			// 		}else {
			// 			_this.onToast(fail.errMsg)
			// 		}
			// 	},
			// })
			// })
			// });
		},
		// 支付提示，跳转到订单界面
		// onToast(msg) {
		// 	this.$refs.uToast.show({
		// 		message: msg,
		// 		complete() {
		// 			uni.switchTab({
		// 				url: "/pages/tab_bar/order/order",
		// 			});
		// 		},
		// 	});
		// },
		getFoodCartShopCouponList() {
			// 优惠券
			this.$api
				.GetFoodCartShopCouponList({
					channelValue: this.FType + 1,
					deskId: this.deskId
				})
				.then((res) => {
					this.coupons = res.data;
				});
		},
		// 继续加菜
		addFoods() {
			uni.switchTab({
				url: '/pages/tab_bar/classify/classify'
			});
		},

		// 获取已下单数据
		async getOrdered() {
			const res = await this.$api.getOrderedList({
				deskId: this.deskId,
				orderId: this.orderId
			});
			// console.log(res);
			// 处理返回数据
			this.orderedList =
				res.data.detail?.length === 0
					? []
					: res.data.detail.map((im) => {
							return {
								orderId: im.orderId,
								number: im.number,
								name: im.name,
								specName: im.specName,
								quantity: im.quantity,
								allAmount: im.allAmount,
								price: im.price,
								image: im.image,
								itemType: im.itemType,
								detailList: im.detailList,
								feedTasteNames: im.feedTasteNames
							};
					  });
		},

		// 提交订单
		async submitOrder() {
			this.disabled = true;
			const res = await this.$api.placeOrder({
				orderId: this.orderId,
				deskId: this.deskId,
				remark: this.remark
			});
			uni.navigateTo({
				url: '/pages/order/confirm_success'
			});
			// uni.navigateTo({
			//   url: '/pages/pay/pay_order/index'
			// });
			this.disabled = false;
		},
		// 展示更多推荐菜
		onMore() {
			if (this.isMore) {
				this.recommendList = JSON.parse(JSON.stringify(this.allRecommendList.slice(0, 3)));
			} else {
				this.recommendList = JSON.parse(JSON.stringify(this.allRecommendList));
			}
			this.isMore = !this.isMore;
		},
		// onMinus(item,index) {
		// 	// 减数量
		// 	if(item.number < 1) return
		// 	this.allRecommendList[index].number = this.allRecommendList[index].number -1
		// 	this.recommendList[index].number = this.recommendList[index].number-1
		// },
		async onAdd(item, index) {
			// 加数量
			// this.allRecommendList[index].number = this.allRecommendList[index].number + 1
			// this.recommendList[index].number = this.recommendList[index].number + 1
			const res = await this.$api.GetSpecBySubId({
				FSubItemID: item.id,
				storeId: this.stock.id,
				specId: item.specId
			});
			this.$set(item, 'materials', res.data);
			this.productData = item;
			this.isVisable = true;
		},
		addToCart(product) {
			// 加入购物车
			this.$api
				.AddShoppingCart({
					FFoodID: product.FFoodID || product.id,
					FQty: product.number || 1,
					feed_ids: product.feed_ids || [],
					tast_ids: product.tast_ids || [],
					FFoodSpecID: product.FFoodSpecID || product.specId,
					deskId: this.deskId,
					orderId: this.orderId
				})
				.then((res) => {
					this.getCat();
					this.closeVisable();
				});
		},
		closeVisable() {
			this.isVisable = false;
			this.productData = {};
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	height: auto;
	padding: 0 30rpx 120rpx 30rpx;

	.head {
		.tabs {
			.sel {
				height: 84rpx;
				background: #fff;
				font-weight: 600;
				color: #111;
				border-radius: 10rpx 30rpx 0rpx 0rpx;
			}

			.ser {
				height: 84rpx;
				background: #fff;
				font-weight: 600;
				color: #111;
				border-radius: 30rpx 10rpx 0rpx 0rpx;
			}

			.nosel {
				height: 74rpx;
				color: #666;
				background: #ededed;
				border-radius: 10rpx 0 0 0;
			}

			.noser {
				height: 74rpx;
				color: #666;
				background: #ededed;
				border-radius: 0 10rpx 0 0;
			}
		}
	}
	// 菜品推荐
	.recommend-box {
		border-radius: 10rpx;
		background-color: #fff9ed;

		.title {
			padding: 20rpx 30rpx 0;
			color: #333333;
			font-size: 24rpx;
		}

		.more {
			display: flex;
			justify-content: center;
			padding-bottom: 30rpx;
		}
	}
}

.footer {
	background-color: #ffffff;
	z-index: 10;
	position: fixed;
	bottom: 0;
	left: 0;
	width: 750rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 10rpx 30rpx 60rpx 30rpx;

	button {
		text-align: center;
		padding: 0;
		line-height: 90rpx;
		color: #111111;
		font-size: 30rpx;
		width: 280rpx;
		height: 90rpx;
		font-weight: bold;
		margin: 0;
		border-radius: 45rpx 0 0 45rpx;
	}

	.button {
		// text-align: center;
		// padding: 0;
		// line-height: 90rpx;
		// color: #111111;
		// font-size: 30rpx;
		// width: 280rpx;
		// height: 90rpx;
		// font-weight: bold;
		background: linear-gradient(34deg, #f3c45d, #edac2f);
		border-radius: 0 45rpx 45rpx 0;
		// border-radius: 45rpx;
		// margin: 0;
	}
}

// 已下单
.placeOrder {
	.is-show {
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: #b1b1b1;
		font-size: 30rpx;
	}
}
.del {
	text-decoration: line-through;
}
</style>
